package com.example.zhyq.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.entity.ParkBean
import com.example.base.entity.ParkBeanItem
import com.example.base.entity.Res
import com.example.base.net.ApiService

class ParkDataSource(val apiService: ApiService, val para: String, val type:String) : PagingSource<Int,ParkBeanItem>(){
    override fun getRefreshKey(state: PagingState<Int, ParkBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkBeanItem> {
        try {
            //当前页码数
            val page = params.key ?: 1
            var res : Res<ParkBean>?=null

            if (type == "类型") {
                res = apiService.getParkByType(para)
            }else if (type=="状态") {
                res = apiService.getParksByStatus(para)
            }else if (type=="区域"){
                res = apiService.getParksByAreaId(para.toInt())
            }

            val prePage = if (page!=1) page-1 else null
            val nextPage = if (res?.data?.size!=0) page+1 else null
            //return LoadResult.Page(res!!.data,prePage,nextPage)
            return LoadResult.Page(res!!.data.sortedByDescending { it.id },prePage,nextPage)
        }catch (e:Exception) {
            return LoadResult.Error(e)
        }
    }

}